<?php

namespace app\comapi\controller;

use app\common\controller\Frontend;
use app\common\model\banxi\say\SayTeachSentence;
use app\common\model\banxi\Sms as SmsModel;
use app\common\model\banxi\student\Student;
use app\common\service\queue\QueueService;
use app\common\service\SmsService;
use app\common\service\WeAppletService;
use ba\Random;
use think\facade\Validate;

class Sms extends Frontend
{
    protected array $noNeedLogin = ['*'];

    protected array $noNeedPermission = ['*'];

    public function initialize(): void
    {
        parent::initialize();
    }

    /**
     * 发送验证码
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="event", type="string", required=true, description="事件名称")
     */
    public function send()
    {
        $phone = $this->request->post("phone");
        $type = $this->request->post("type");
        $type = $type ?: 'userLogin';

        if (!$phone || !Validate::regex($phone, "^1\d{10}$")) {
            $this->fail(__('手机号不正确'));
        }
        $SmsService = new SmsService;
        $last = $SmsService->get($phone, $type);
        if ($last && time() - $last['createtime'] < 60) {
            $this->fail(__('发送频繁'));
        }
        $ip = $this->request->ip();
        $ipSendTotal = SmsModel::where(['ip' => $ip])->whereTime('updateTime', '-1 hours')->count();
        if ($ipSendTotal >= 5) {
            $this->fail(__('发送频繁'));
        }
        if ($type) {
            $userinfo = Student::getByPhone($phone);
            if ($type == 'userLogin' && !$userinfo) {
                //未注册
                $this->fail(__('账号不存在'));
            } elseif (in_array($type, ['changemobile']) && $userinfo) {
                //被占用
                $this->fail(__('已被占用'));
            } elseif (in_array($type, ['changepwd', 'resetpwd']) && !$userinfo) {
                //未注册
                $this->fail(__('未注册'));
            }
        }
        $code = Random::build('numeric', 6);
        $info = (new SmsModel)->saveCode($phone, $code, $type, $ip);
        if (!$info) {
            $this->fail(__('发送失败'));
        }
        $ret = $SmsService->sendSms($phone, $code);
        if ($ret) {
            $this->ok(__('发送成功'));
        } else {
            $this->fail(__('发送失败'));
        }
    }

    public function ceshi()
    {
        $sayTeachSentence = new SayTeachSentence();
        // 获取所有根节点（parentId为0的记录）
        $list = $sayTeachSentence->where('parentId', 0)->field('id,coreVocabulary')->select()->toArray();
        $coreVocabularyLists = array_column($list, 'coreVocabularyList');
        // 提取所有parentIds用于批量查询子节点
        $parentIds = array_column($list, 'id');
        // 优化：批量查询所有子节点，而不是逐个查询
        $childrenList = $sayTeachSentence->where('parentId', 'in', $parentIds)->field('id,parentId,coreVocabulary')->select()->toArray();
        $childCoreVocabularyLists = array_column($childrenList, 'coreVocabularyList');
        $coreVocabularyLists = array_merge($coreVocabularyLists, $childCoreVocabularyLists);
        if ($coreVocabularyLists) {
            $this->processSayTeachSentences($coreVocabularyLists);
        }
        echo '成功';
    }

    private function processSayTeachSentences($list)
    {
        if (!$list) {
            return true;
        }

        $queueService = new QueueService();
        $allVocabulary = [];

        foreach ($list as $item) {
            // 确保coreVocabularyList是数组格式
            $vocabularyList = is_array($item['coreVocabularyList']) ?
                $item['coreVocabularyList'] :
                json_decode($item['coreVocabularyList'], true);

            if ($vocabularyList && is_array($vocabularyList)) {
                $allVocabulary = array_merge($allVocabulary, $vocabularyList);
            }
        }

        // 批量添加任务，避免多次调用队列
        if (!empty($allVocabulary)) {
            $queueService->addSayWordSplitJob($allVocabulary);
        }

        return true;
    }


}